package com.dhms.vostok1.ui.main.mine

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.dhms.mine.R
import com.dhms.mine.databinding.FragmentMineBinding
import com.dhms.uikit.DialogBuilder
import com.dhms.uikit.qrCodeScan.QRCodeScanActivity
import com.dhms.vostok1.adapter.BaseListAdapter
import com.dhms.vostok1.data.BaseListItem
import com.dhms.vostok1.data.OnBaseListItemClickListener
import com.dhms.vostok1.data.device_center.DeviceListItemData
import com.dhms.vostok1.model.DeviceViewModel
import com.dhms.vostok1.model.UserViewModel
import com.dhms.vostok1.model.WebSocketViewModel
import com.dhms.vostok1.ui.main.MainActivityInterface
import com.dhms.vostok1.utils.AppFeatureManager
import com.dhms.vostok1.utils.NetworkState
import com.dhms.vostok1.utils.Utils
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.zxing.client.android.Intents
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanIntentResult
import com.journeyapps.barcodescanner.ScanOptions

class MineFragment : Fragment() {
    private var _binding: FragmentMineBinding? = null
    private val binding get() = _binding!!

    private lateinit var recordBottomSheet: BottomSheetDialogFragment
    private val deviceViewModel: DeviceViewModel by activityViewModels()
    private val userViewModel: UserViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentMineBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.viewModel = userViewModel
        binding.lifecycleOwner = viewLifecycleOwner

        setOptionList()

        setToolBar()
    }

    private fun setToolBar() {
        (activity as MainActivityInterface).setNotificationBadge(binding.topAppBar)
        binding.topAppBar.setOnMenuItemClickListener {
            if (WebSocketViewModel.instance.networkChange.value == NetworkState.NETWORK_NO) {
                errorTip(getString(R.string.offline_mode_unavailable))
                false
            } else {
                when (it.itemId) {
                    R.id.menu_notification -> {
                        findNavController().navigate(R.id.action_mineFragment_to_messageCenterFragment)
                        true
                    }
                    R.id.menu_scanning_qr_code -> {
                        val options =
                            ScanOptions().setCaptureActivity(QRCodeScanActivity::class.java)
                        barcodeLauncher.launch(options)

                        true
                    }
                    R.id.menu_nearby_equipment -> {
                        findNavController().navigate(R.id.action_mineFragment_to_nearbyDevicesFragment)
                        true
                    }
                    else -> false
                }
            }
        }
    }

    private val barcodeLauncher = registerForActivityResult(
        ScanContract()
    ) { result: ScanIntentResult ->
        if (result.contents == null) {
            val originalIntent = result.originalIntent
            if (originalIntent == null) {
                Log.d(TAG, "Cancelled scan")
            } else if (originalIntent.hasExtra(Intents.Scan.MISSING_CAMERA_PERMISSION)) {
                Log.d(
                    TAG,
                    "Cancelled scan due to missing camera permission"
                )
                Toast.makeText(
                    activity,
                    "请打开相机权限",
                    Toast.LENGTH_LONG
                ).show()
            }
        } else {
            Log.d(TAG, "Scanned")

            val deviceId = Utils.getQueryParameter(result.contents, Utils.deviceId)?.toLongOrNull()
            if (deviceId == null) {
                (activity as MainActivityInterface).showToast(
                    message = "获取不到设备id",
                )
                return@registerForActivityResult
            }

            (activity as MainActivityInterface).showToast(
                message = "正在获取设备信息",
                isLoading = true,
                timeOut = 15
            )

            deviceViewModel.getDeviceByDeviceId(deviceId) {
                (activity as MainActivityInterface).hideToast()
                if (it == null) {
                    (activity as MainActivityInterface).showToast(
                        message = "获取设备信息失败",
                    )
                } else {
                    deviceDetailJump(it)
                }
            }

        }
    }

    private fun deviceDetailJump(deviceData: DeviceListItemData) {
        deviceViewModel.setCurrentDevice(deviceData)
        deviceViewModel.clearDevicePartsData()
        val url = "${AppFeatureManager.deviceDetailUrl}?deviceId=${deviceData.deId}"
        val action = MineFragmentDirections.actionMineFragmentToWebViewFragment(url)
        findNavController().navigate(action)
    }

    private fun setOptionList() {
        val logoutConfirmDialog =
            DialogBuilder(requireContext()).setTitle(getString(R.string.logout_confirm_message))
                .setOnPositiveButtonClickListener {
                    (activity as MainActivityInterface).logout()
                    true
                }.setOnNegativeButtonClickListener().createDialog()
        val onBaseListItemClickListener: OnBaseListItemClickListener = {
            when (it) {
                0 -> {
                    if (WebSocketViewModel.instance.networkChange.value == NetworkState.NETWORK_NO) {
                        errorTip(getString(R.string.offline_mode_unavailable))
                    } else {
                        findNavController().navigate(R.id.action_mineFragment_to_privacyFragment)
                    }
                }
                1 -> {
                    findNavController().navigate(R.id.action_mineFragment_to_aboutFragment)
                }
                2 -> {
                    if (WebSocketViewModel.instance.networkChange.value == NetworkState.NETWORK_NO) {
                        errorTip(getString(R.string.offline_mode_unavailable))
                    } else {
                        findNavController().navigate(R.id.action_mineFragment_to_accountFragment)
                    }
                }
                3 -> {
                    logoutConfirmDialog.show()
                }
            }
        }
        binding.mineOptionList.adapter = BaseListAdapter(
            requireContext(), listOf(
                BaseListItem(
                    itemPrefixIcon = ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.ic_mine_option_privacy,
                        null
                    ),
                    itemTitle = getString(R.string.mine_option_privacy),
                    itemSuffixIcon = ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.ic_arrow_right,
                        null
                    )
                ),
                BaseListItem(
                    itemPrefixIcon = ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.ic_mine_option_about,
                        null
                    ),
                    itemTitle = getString(R.string.mine_option_about),
                    itemSuffixIcon = ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.ic_arrow_right,
                        null
                    )
                ),
                BaseListItem(
                    itemPrefixIcon = ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.ic_mine_option_account,
                        null
                    ),
                    itemTitle = getString(R.string.mine_option_account),
                    itemSuffixIcon = ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.ic_arrow_right,
                        null
                    )
                ),
                BaseListItem(
                    itemPrefixIcon = ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.ic_mine_option_logout,
                        null
                    ),
                    itemTitle = getString(R.string.mine_option_logout),
                    itemSuffixIcon = ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.ic_arrow_right,
                        null
                    )
                ),
            ),
            onBaseListItemClickListener
        )

        fun showAudioRecord() {

        }
    }

    private fun errorTip(message: String?) {
        (activity as MainActivityInterface).showToast(
            R.drawable.ic_fail,
            message,
            false,
            2
        )
    }

    companion object {
        const val TAG = "MineFragment"
    }
}
